import React, { useMemo } from 'react';

import Editor, { loader } from '@monaco-editor/react';
import {
  useNodeStore,
  useConnectionStore,
  CodeCompiler,
  useVariableStore,
} from 'codeck';
import { Notification, Message } from '@arco-design/web-react';
import { useRegistryStore } from '@/registry/store';

export const CodeEditor: React.FC = React.memo(() => {

  const { nodeMap, nodeDefinition } = useNodeStore((state) => ({
    nodeMap: state.nodeMap,
    nodeDefinition: state.nodeDefinition,
  }));
  const connections = useConnectionStore((state) => state.connections);
  const variableMap = useVariableStore((state) => state.variableMap);
  const inited = useRegistryStore((state) => state.inited);

  const handleKeyupC = (e: MouseEvent) => {
    if (e.button === 1) {
      let monacoc = loader.__getMonacoInstance();
      if (monacoc) {
        navigator.clipboard.writeText(monacoc.editor.getEditors()[0].getValue()).then(() => {
          Message.success({
            id: 'copyCode',
            content: '代码复制成功',
            style: {
              marginTop: 45
            }
          })
        });
        return;
      }

    }
  }

  window.addEventListener('mousedown', handleKeyupC);


  const code = useMemo(() => {
    // if (inited === false) {
    //   return '// [Plugin has not been inited]';
    // }

    try {
      const text = new CodeCompiler().generate();
      let monacoc = loader.__getMonacoInstance();
      monacoc?.editor.getEditors()[0].getAction('editor.action.formatDocument')._run();
      return text;
    } catch (err) {
      console.warn(err);
      Notification.error({
        id: 'codeErroe',
        style: { width: 500, marginTop: 45 },
        title: '代码编译出错',
        content:
          '节点编译成代码失败，请检查节点。具体错误请查看控制台',
      })
    }

  }, [nodeMap, nodeDefinition, connections, variableMap, inited]);
  return (

    <div className="h-full w-full">
      <Editor
        theme="vs-dark"
        language="javascript"
        value={code}
        options={{ readOnly: false, autoIndent: 'brackets', automaticLayout: true, }}
        loading="搬砖喵正在飞速加载中..."
        onChange={loadingdao3}
      />
    </div>
  );
});
CodeEditor.displayName = 'CodeEditor';

loader.config({ paths: { vs: "https://cdn.staticfile.net/monaco-editor/0.45.0/min/vs" } });
let isdao3ok = false;

async function loadingdao3() {
  const monacoTypesUrl = 'https://static.dao3.fun/block/QmRDNJDhUzCfpB8PW9NvfbTARyjmjwSS5oj4Q8tCFHf9DY'
  const libSource = await (await fetch(monacoTypesUrl)).text();
  const monacoTypesUrl2 = 'https://static.codemao.cn/pickduck/r1UQu15X0.ts?hash=FiDK2KZCGSfbF2WpBein_UIS0RzV'
  const libSource2 = await (await fetch(monacoTypesUrl2)).text();
  if (isdao3ok) return;
  let monacoc = loader.__getMonacoInstance();
  monacoc?.languages.typescript.javascriptDefaults.addExtraLib(libSource, "ts:filename/Game.d.ts");
  monacoc?.languages.typescript.javascriptDefaults.addExtraLib(libSource2, "ts:filename/GameUI.d.ts");
  isdao3ok = true;
  monacoc?.editor.onDidChangeMarkers(() => {
    const codeWarn = monacoc?.editor.getModelMarkers({}).filter((e) => { return e.code != '6133' && e.code != '80001' && e.code != '6198' });
    if (codeWarn?.length) {
      Notification.warning({
        id: 'codeWarn',
        style: { width: 300, marginTop: 45 },
        duration: 999999999,
        title: '代码有错误',
        content:
          '当前有' + codeWarn.length + '处错误，请及时修正节点。\n首个错误：' + codeWarn[0].message,
      })
    } else {
      Notification.remove('codeWarn')
    }
  })

}


